const fs = require('fs');
const spider = require('./tools/spider');
const { formatDate } = require('./tools/formatDate');
const { getTwoArrayDiff, formatUserName } = require('./tools/getTwoArrayDiff');
const { getWinnerNum, judgeUserIsInGameSeat, parseNumber, getArrayIndex } = require('./utils/util');
const { log } = require('./utils/log');

// [ '2020-04-28', '2020-04-28 23:58:37', 1588089517 ]
let formatStart = null;
let formatEnd = null;
let userListJson = [];
let gameListJson = [];
let simpleUserlistJson = [];

// 初始化数据
let initData = () => {
    formatStart = null;
    formatEnd = null;
    userListJson = [];
    gameListJson = [];
    simpleUserlistJson = [];
}

// 获取用户信息
let getUserList = async () => {
    log('获取用户列表信息');
    usernameJson = require('./datalist/username.json');
    let userlistres = await spider.getDdzUserList();
    userListJson = formatUserName(userlistres, usernameJson)
    return userListJson;
}

// 获取用户简要信息
let getSimpleUserList = async () => {
    log('获取用户简要信息');
    userListJson.forEach(item => {
        const { gameuserid, headimg, formatUserName } = item;
        let score = '0', finalScore = 0, origin = '0';
        simpleUserlistJson.push({ gameuserid, headimg, formatUserName, score, finalScore, origin });
    });
    // log(simpleUserlistJson)
    return simpleUserlistJson;
}

// 获取赛事信息
let getGameList = async (time) => {
    log('获取赛事列表信息');
    let res = await spider.getDdzGameList(time);
    gameListJson.push(...res);
}

// 按时间过滤赛事结果
let filterGameListByTime = async () => {
    let start = formatStart[2], end = formatEnd[2];
    let startIndex = getArrayIndex(gameListJson, start);
    let endIndex = getArrayIndex(gameListJson, end);
    let filterArr = gameListJson.slice(startIndex, endIndex+1 );
    gameListJson = filterArr;
    log(startIndex,endIndex,'过滤游戏结果长度', gameListJson.length)
    return filterArr;
}

// 遍历赛事数据统计结果
let getFinalGameList = async () => {
    gameListJson.forEach(gameItem => {
        const { seats } = gameItem;
        // 1.获取大赢家数量  房费默认值 5
        let totalWinner = getWinnerNum(seats), fee = 5;
        // 2.循环 更新数据
        simpleUserlistJson.forEach(userItem => {
            let res = judgeUserIsInGameSeat(userItem.gameuserid, seats);
            if (res) {
                const { score, totalscore, iswiner } = res;
                if (iswiner) {
                    if (score >= 0 && score <= 3) fee = 0;              // 低于3分不发房费，3分需要发
                    let number = 3 * score - fee;
                    userItem.score += parseNumber(number);
                    userItem.finalScore += Number(number);
                    userItem.origin += parseNumber(score);
                } else {
                    let number = 3 * score;
                    userItem.score += parseNumber(number);
                    userItem.finalScore += Number(number);
                    userItem.origin += parseNumber(score);
                }
            }
        });
    });
    // 最后数组排序  finalScore 从高到低
    simpleUserlistJson.sort((a, b) => { return b.finalScore - a.finalScore });
    return simpleUserlistJson;
}

let entry = async (req, res) => {
    // 初始化数据
    initData();
    // 计算数据
    const { start, end } = req.body;
    if(start < end ) return res.end(JSON.stringify({ code: -1, msg: '时间输入错误'}));
    formatStart = formatDate(start);
    formatEnd = formatDate(end);
    log('\n', formatStart, formatEnd)
    await getUserList();
    await getSimpleUserList();
    await getGameList(formatStart[0]);
    if(formatEnd[0] != formatStart[0]) await getGameList(formatEnd[0]);
    await filterGameListByTime();
    let result = await getFinalGameList();
    res.end(JSON.stringify({ code: 1, msg: '获取结果成功', data: result}));
}

module.exports = { entry };